import {recentlyList, recentlyDel, recentlyDelFile} from "@/api/recently.ts";
import useTable from "@/hooks/useTable.ts";
import {DataType} from "@/api/recently.ts";
import {Button, Flex, Table, TableColumnsType} from "antd";
import { useNavigate } from 'react-router-dom'
import {useEffect, forwardRef, useImperativeHandle, useRef, useState} from "react";
import dayjs from "dayjs";
import RecentlyDelModal from "@/components/recently/RecentlyDelModal.tsx";

interface IProps {
    name: string
}

interface IRecentlyDelModalRefProps {
    showModal: () => void
}

const RecentlyTable = forwardRef(({ name }: IProps, ref) => {
    const { dataSource, getList, del } = useTable(recentlyList, { name })
    const [selectRecentlyUID, setSelectRecentlyUID] = useState<string>('')
    const [selectPath, setSelectPath] = useState<string>('')
    const recentlyDelModalRef = useRef(null)
    const navigate = useNavigate()
    const details = (path: string) => {
        navigate(`/recently/details?path=${path}`)
    }
    useEffect(() => {
        getList()
    }, []);
    const delOpen = (recentlyUID: string, path: string) => {
        if (recentlyDelModalRef.current) {
            (recentlyDelModalRef.current as IRecentlyDelModalRefProps).showModal()
            setSelectRecentlyUID(recentlyUID)
            setSelectPath(path)
        }
    }
    const delOk = async () => {
        if (selectRecentlyUID) {
            await recentlyDelFile(selectPath)
            del(recentlyDel, [selectRecentlyUID])
            setSelectRecentlyUID('')
            setSelectPath('')
        }
    }
    useImperativeHandle(ref, () => ({ getList }))
    const columns: TableColumnsType<DataType> = [
        {
            title: '名称',
            dataIndex: 'name',
            // render: (text: string, { fileUID, type }: DataType) => <a onClick={() => fileListTable(fileUID, type, text)}>{text}</a>,
        },
        {
            title: '备注',
            dataIndex: 'describe',
            render: (text) => <div>{text}</div>
        },
        {
            title: '更新时间',
            dataIndex: 'time',
            render: (time) => <div>{ dayjs(time).format('YYYY-MM-DD HH:mm:ss') }</div>
        },
        {
            title: '操作',
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            render: (_, { recentlyUID, path }) => (
                <Flex gap='middle' wrap>
                    <Button type='link' onClick={() => details(path)}>详情</Button>
                    <RecentlyDelModal delOk={delOk} setSelectRecentlyUID={setSelectRecentlyUID} ref={recentlyDelModalRef} btn={<Button type='link' danger onClick={() => delOpen(recentlyUID, path)}>删除</Button>} />
                </Flex>
            )
        }
    ];
    return (
        <Table<DataType> pagination={false} scroll={{ x: 650 }} style={{ overflow: 'auto' }} dataSource={dataSource} columns={columns} />
    )
})

export default RecentlyTable